import { createStore } from 'vuex'
import axios from 'axios'

// API基础URL
const API_BASE_URL = '/v1/admin'

export default createStore({
  state: {
    token: localStorage.getItem('admin_token') || '',
    userInfo: JSON.parse(localStorage.getItem('admin_info') || '{}'),
    sidebarCollapsed: false
  },
  getters: {
    isLoggedIn: state => !!state.token,
    userInfo: state => state.userInfo,
    sidebarCollapsed: state => state.sidebarCollapsed
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('admin_token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('admin_info', JSON.stringify(userInfo))
    },
    CLEAR_AUTH(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_info')
    },
    TOGGLE_SIDEBAR(state) {
      state.sidebarCollapsed = !state.sidebarCollapsed
    }
  },
  actions: {
    // 登录
    async login({ commit }, credentials) {
      try {
        const response = await axios.post(`${API_BASE_URL}/login`, credentials)
        const { token, admin } = response.data
        
        // 设置axios默认headers
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
        
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', admin)
        return Promise.resolve(response.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getUserInfo({ commit }) {
      try {
        const response = await axios.get(`${API_BASE_URL}/info`)
        commit('SET_USER_INFO', response.data.admin)
        return Promise.resolve(response.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 登出
    async logout({ commit }) {
      try {
        await axios.post(`${API_BASE_URL}/logout`)
        commit('CLEAR_AUTH')
        return Promise.resolve()
      } catch (error) {
        commit('CLEAR_AUTH')
        return Promise.reject(error)
      }
    },
    
    // 切换侧边栏
    toggleSidebar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    }
  }
}) 